package cn.ruanyun.backInterface.modules.rongyun.serviceimpl;

import cn.hutool.http.HttpUtil;
import cn.ruanyun.backInterface.common.constant.CommonConstant;
import cn.ruanyun.backInterface.common.exception.RuanyunException;
import cn.ruanyun.backInterface.common.utils.*;
import cn.ruanyun.backInterface.common.vo.Result;
import cn.ruanyun.backInterface.modules.base.pojo.User;
import cn.ruanyun.backInterface.modules.base.pojo.UserRole;
import cn.ruanyun.backInterface.modules.base.service.UserRoleService;
import cn.ruanyun.backInterface.modules.base.service.mybatis.IRoleService;
import cn.ruanyun.backInterface.modules.base.service.mybatis.IUserRoleService;
import cn.ruanyun.backInterface.modules.base.service.mybatis.IUserService;
import cn.ruanyun.backInterface.modules.business.group.pojo.Group;
import cn.ruanyun.backInterface.modules.business.group.service.IGroupService;
import cn.ruanyun.backInterface.modules.business.platformServicer.pojo.PlatformServicer;
import cn.ruanyun.backInterface.modules.business.staffManagement.pojo.StaffManagement;
import cn.ruanyun.backInterface.modules.business.staffManagement.service.IStaffManagementService;
import cn.ruanyun.backInterface.modules.business.storeServicer.pojo.StoreServicer;
import cn.ruanyun.backInterface.modules.rongyun.Vo.RongyunLoginVo;
import cn.ruanyun.backInterface.modules.rongyun.dto.GroupInfoCreate;
import cn.ruanyun.backInterface.modules.rongyun.dto.GroupUser;
import cn.ruanyun.backInterface.modules.rongyun.dto.GroupUserVO;
import cn.ruanyun.backInterface.modules.rongyun.dto.RongyunImDto;
import cn.ruanyun.backInterface.modules.rongyun.mapper.RongyunMapper;
import cn.ruanyun.backInterface.modules.rongyun.pojo.Rongyun;
import cn.ruanyun.backInterface.modules.rongyun.service.IRongyunService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.api.client.util.Lists;
import io.rong.RongCloud;
import io.rong.models.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 融云接口实现
 * @author fei
 */
@Slf4j
@Service
@Transactional
public class IRongyunServiceImpl extends ServiceImpl<RongyunMapper, Rongyun> implements IRongyunService {


    RongCloud imClient;

    public static final String APPKEY = "x4vkb1qpxg9mk";

    public static final String APP_SECRET = "KW9iLOtq2309";


    @Autowired
    private IUserService userService;

    @Autowired
    private IUserRoleService iUserRoleService;

    @Autowired
    private IGroupService iGroupService;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IStaffManagementService staffManagementService;

    @PostConstruct
    public void init() {

        imClient = RongCloud.getInstance(APPKEY, APP_SECRET);

    }





    @Override
    public Boolean addUser(String id, String name, String portrait) throws RuanyunException {
        try {

            TokenResult result = imClient.user.getToken(id, name, portrait);
            if(result.getCode() == 200){

                Optional.ofNullable(userService.getById(id))
                        .ifPresent(user -> {

                            user.setImToken(result.getToken());
                            userService.updateById(user);
                        });
                return true;
            }else{
                return false;
            }
        } catch (Exception e) {
            throw new RuanyunException("系统异常");
        }
    }

    @Override
    public boolean updateUser(String id, String name, String portrait) throws RuanyunException {
        try {

            CodeSuccessResult result = imClient.user.refresh(id, name, portrait);
            if(result.getCode() == 200){
                return true;
            }else{
                throw new RuanyunException("同步更新im用户出错");
            }
        } catch (Exception e) {
            throw new RuanyunException("系统异常");
        }
    }


    @Override
    public String getToken(String userId, String name, String portraitUri) throws RuanyunException {
        System.out.println(userId + name + portraitUri);
        try {

            TokenResult result = imClient.user.getToken(userId, name, portraitUri);
            if (result.getCode() == 200) {

                return result.getToken();
            }else {

                throw new RuanyunException("获取用户token失败！");
            }
        }catch (Exception e) {

            throw new RuanyunException("系统异常");
        }
    }

    @Override
    public String checkOnlineResult(String userId) throws RuanyunException {

        try {

            CheckOnlineResult result = imClient.user.checkOnline(userId);
            if (result.getCode() == 200) {

                return result.getStatus();
            }else {

                throw new RuanyunException("获取用户在线状态失败！");
            }
        }catch (Exception e) {

            throw new RuanyunException("系统异常");
        }
    }

    @Override
    public GroupInfoCreate createGroup(String userId, String merchantId) throws Exception {


       /* RongCloud imClient = RongCloud.getInstance(APPKEY, APP_SECRET);
        // 创建群组返回数据
        GroupInfoCreate groupInfoCreate = new GroupInfoCreate();

        // 群组用户列表
        List<GroupUser> groupUsers = new ArrayList<>();

        // 查询是否建过群
        List<Group> groups = iGroupService.list(Wrappers.<Group>lambdaQuery()
                .eq(Group::getUserId, userId).eq(Group::getStoreId, merchantId));

        // 建过群，检查是否有商检客服
        if(ToolUtil.isNotEmpty(groups)){

            Group group = groups.get(0);

            // 群组中没有商家客服，检查商家有没有客服
            if(ToolUtil.isEmpty(group.getStoreServicerId())){
                // 查询商家客服
                List<StaffManagement> staffManagements = staffManagementService.getStoreServiceList(merchantId);

                if (ToolUtil.isEmpty(group.getPlatformServicerId())) {

                    //查询平台客服
                    List<UserRole> userRoles = iUserRoleService.list(Wrappers.<UserRole>lambdaQuery()
                            .eq(UserRole::getRoleId, roleService.getIdByRoleName(CommonConstant.PC_SERVICE)));

                    if (ToolUtil.isNotEmpty(userRoles)) {

                        int chooseDindex = new Random().nextInt(userRoles.size());
                        // 选择客服ID
                        String servicePcId = userRoles.get(chooseDindex).getUserId();

                        String imId = Optional.ofNullable(userService.getById(servicePcId)).map(User::getImId).orElse(null);
                        group.setPlatformServicerId(imId);
                    }

                }

                // 商家有客服
                if(ToolUtil.isNotEmpty(staffManagements)){
                    int chooseDindex = new Random().nextInt(staffManagements.size());
                    // 选择客服ID
                    String merchantServiceId = staffManagements.get(chooseDindex).getStaffId();
                    String merchatImId = Optional.ofNullable(userService.getById(merchantServiceId)).map(User::getImId).orElse(null);

                    try {
                        CodeSuccessResult result = imClient.group.join(new String[]{merchatImId}, group.getGroupId(), group.getGroupName());

                        if(result.getCode() == 200){
                            group.setStoreServicerId(merchatImId);
                            iGroupService.updateById(group);

                            Optional.ofNullable(userService.getById(merchantServiceId))
                                    .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "merchantServicer")));

                            Optional.ofNullable(userService.getOne(Wrappers.<User>lambdaQuery()
                                    .eq(User::getImId, group.getPlatformServicerId())))
                                    .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "platformServicer")));

                            Optional.ofNullable(userService.getOne(Wrappers.<User>lambdaQuery()
                                    .eq(User::getImId, userId)))
                                    .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "user")));

                            Optional.ofNullable(userService.getById(group.getStoreId()))
                                    .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "merchant")));

                            groupInfoCreate.setGroupUsers(groupUsers);
                            groupInfoCreate.setGroupId(group.getGroupId());
                            groupInfoCreate.setGroupName(group.getGroupName());
                            return groupInfoCreate;
                        } else {
                            throw new RuanyunException("拉客服进群失败");
                        }
                    } catch (Exception e) {
                        throw new RuanyunException("系统异常");
                    }
                } else {
                    //商家没有客服
                    Optional.ofNullable(userService.getOne(Wrappers.<User>lambdaQuery()
                            .eq(User::getImId, group.getPlatformServicerId())))
                            .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "platformServicer")));

                    Optional.ofNullable(userService.getOne(Wrappers.<User>lambdaQuery()
                            .eq(User::getImId, userId)))
                            .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "user")));

                    Optional.ofNullable(userService.getOne(Wrappers.<User>lambdaQuery()
                            .eq(User::getImId, group.getStoreId())))
                            .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "merchant")));

                    groupInfoCreate.setGroupUsers(groupUsers);
                    groupInfoCreate.setGroupId(group.getGroupId());
                    groupInfoCreate.setGroupName(group.getGroupName());
                    return groupInfoCreate;

                }
            } else {
                // 群组中有商家客服，直接返回
                Optional.ofNullable(userService.getOne(Wrappers.<User>lambdaQuery()
                        .eq(User::getImId, group.getStoreServicerId())))
                        .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "merchantServicer")));

                Optional.ofNullable(userService.getOne(Wrappers.<User>lambdaQuery()
                        .eq(User::getImId, group.getPlatformServicerId())))
                        .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "platformServicer")));

                Optional.ofNullable(userService.getOne(Wrappers.<User>lambdaQuery()
                        .eq(User::getImId, userId)))
                        .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "user")));

                Optional.ofNullable(userService.getOne(Wrappers.<User>lambdaQuery()
                        .eq(User::getImId, group.getStoreId())))
                        .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "merchant")));

                groupInfoCreate.setGroupUsers(groupUsers);
                groupInfoCreate.setGroupId(group.getGroupId());
                groupInfoCreate.setGroupName(group.getGroupName());
                return groupInfoCreate;
            }
        }

        // 商家客服
        String merchantServiceId = "";

        List<StaffManagement> staffManagements = staffManagementService.getStoreServiceList(merchantId);

        if(ToolUtil.isNotEmpty(staffManagements)){

            int chooseDindex = new Random().nextInt(staffManagements.size());
            merchantServiceId = staffManagements.get(chooseDindex).getStaffId();
        }

        // 要添加的群组成员
        List<String> members = new ArrayList<>();


        // 平台客服
        String platformServiceId = Optional.ofNullable(ToolUtil.setListToNul(iUserRoleService.list(Wrappers.<UserRole>lambdaQuery()
                .eq(UserRole::getRoleId, roleService.getIdByRoleName(CommonConstant.PC_SERVICE)))))
                .map(userRoles -> {

                    int chooseDindex = new Random().nextInt(userRoles.size());
                    String platformServiceIdReturn = userRoles.get(chooseDindex).getUserId();
                    Optional.ofNullable(userService.getById(platformServiceIdReturn))
                            .ifPresent(user -> {

                                groupUsers.add(new GroupUser(user.getId(), user.getAvatar(),
                                        user.getNickName(), "platformServicer"));

                                members.add(user.getImId());

                            });


                    return platformServiceIdReturn;
                }).orElse(null);



        // 用户
        Optional.ofNullable(userService.getById(userId))
                .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "user")));
        members.add(userId);

        // 商家客服
        if(ToolUtil.isNotEmpty(merchantServiceId)){
            Optional.ofNullable(userService.getById(merchantServiceId))
                    .ifPresent(user -> {

                        groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "merchantServicer"));
                        members.add(user.getImId());

                    });

        }

        // 商家
        Optional.ofNullable(userService.getById(merchantId))
                .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "merchant")));

        // 群组id
        // String groupId = ToolUtil.getRandomString(24);// 最大30位
        String groupId = merchantId + "," + userId;

        // 群组名称
        String groupName = userService.getById(merchantId).getNickName();

        groupInfoCreate.setGroupUsers(groupUsers);
        groupInfoCreate.setGroupId(groupId);
        groupInfoCreate.setGroupName(groupName);

        // 创建群组
        CodeSuccessResult result = imClient.group.create(members.toArray(new String[]{}), groupId, groupName);
        if(result.getCode() == 200){
            Group group = new Group();
            group.setGroupId(groupId);
            group.setUserId(userId);
            group.setPlatformServicerId(platformServiceId);
            group.setStoreServicerId(merchantServiceId);
            group.setStoreId(merchantId);
            group.setGroupName(groupName);
            iGroupService.insertOrderUpdateGroup(group);
            return groupInfoCreate;
        }else{

            log.info(result.getErrorMessage());
            throw new RuanyunException("创建群组失败");
        }*/

        /**
        RongCloud rongCloud = RongCloud.getInstance(APPKEY, APP_SECRET);

        GroupInfoCreate groupInfoCreate = new GroupInfoCreate();

        List<GroupUser> groupUsers = Lists.newArrayList();

        Group group = new Group();

        List<String> groupList = Lists.newArrayList();

        // 1. 商家客服
        //1.1 判断当前商家有没有客服，如果有的话，随机选取一个客服
        List<StaffManagement> staffManagements = staffManagementService.getStoreServiceList(merchantId);

        if (ToolUtil.isNotEmpty(staffManagements)) {

            int chooseDindex = new Random().nextInt(staffManagements.size());

            //获取商家客户id
            String storeImId = Optional.ofNullable(userService.getById(staffManagements.get(chooseDindex).getStaffId()))
                    .map(User::getImId).orElse(null);
            group.setStoreServicerId(storeImId);
            groupList.add(storeImId);

            Optional.ofNullable(userService.getById(staffManagements.get(chooseDindex).getStaffId()))
                    .ifPresent(user -> {

                        group.setStoreServicerId(user.getImId());
                        groupList.add(user.getImId());

                        //群组成员
                        groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "storeService"));
                    });

        }else {

            Optional.ofNullable(userService.getById(merchantId)).ifPresent(store -> {

                group.setStoreId(store.getImId());
                groupList.add(group.getStoreId());

                groupUsers.add(new GroupUser(store.getId(), store.getAvatar(), store.getNickName(), "store"));
            });
        }


        //1.2 平台客服
        // 平台客服
        Optional.ofNullable(ToolUtil.setListToNul(iUserRoleService.list(Wrappers.<UserRole>lambdaQuery()
                .eq(UserRole::getRoleId, roleService.getIdByRoleName(CommonConstant.PC_SERVICE)))))
                .ifPresent(userRoles -> {


                    //平台客服id
                    int chooseDindex = new Random().nextInt(userRoles.size());

                    Optional.ofNullable(userService.getById(userRoles.get(chooseDindex).getUserId()))
                            .ifPresent(platformUser -> {

                                groupList.add(platformUser.getImId());
                                group.setPlatformServicerId(platformUser.getImId());

                                //群组成员
                                groupUsers.add(new GroupUser(platformUser.getId(), platformUser.getAvatar(), platformUser.getNickName(), "platformService"));
                            });

                });


        //1.3 我自己
        groupList.add(userId);
        group.setUserId(userId);
        Optional.ofNullable(userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getImId, userId)))
                .ifPresent(myself -> groupUsers.add(new GroupUser(myself.getId(), myself.getAvatar(), myself.getNickName(), "me")));


        String groupName = Optional.ofNullable(userService.getById(merchantId)).map(User::getNickName).orElse("-");

        groupInfoCreate.setGroupUsers(groupUsers);
        groupInfoCreate.setGroupId(userId);
        groupInfoCreate.setGroupName(groupName);


        String groupId = userId + "" + merchantId;
        // 创建群组
        CodeSuccessResult result = imClient.group.create(groupList.toArray(new String[]{}), groupId, groupName);

        if(result.getCode() == 200){

            group.setGroupId(userId);
            group.setUserId(userId);
            group.setGroupName(groupName);
            iGroupService.save(group);

            return groupInfoCreate;
        }else{

            log.info(result.getErrorMessage());
            throw new RuanyunException("创建群组失败");
        }*/



        // 创建群组返回数据
        GroupInfoCreate groupInfoCreate = new GroupInfoCreate();

        // 群组用户列表
        List<GroupUser> groupUsers = new ArrayList<>();

        // 查询是否建过群
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", userId);
        map.put("store_id", merchantId);
        List<Group> groups = iGroupService.listByMap(map);

        System.out.println("是否建群"+ groups);

        // 建过群，检查是否有商检客服
        if(groups.size() > 0){
            Group group = groups.get(0);

            // 群组中没有商家客服，检查商家有没有客服
            if(EmptyUtil.isEmpty(group.getStoreServicerId())){
                // 查询商家客服
                Map<String, Object> map2 = new HashMap<>();
                map2.put("create_by", merchantId);

                // 商家客服角色id  285894394777702400
                map2.put("role_id", "285894394777702400");

                List<UserRole> userRoles = iUserRoleService.listByMap(map2);
                // List<StoreServicer> storeServicers = (List<StoreServicer>) userRoles;
                System.out.println("查询商家客服结果" + userRoles);
                // 商家有客服
                if(userRoles.size() > 0){
                    int chooseDindex = new Random().nextInt(userRoles.size());
                    // 选择客服ID
                    String merchantServiceId = userRoles.get(chooseDindex).getUserId();
                    try {
                        CodeSuccessResult result = imClient.group.join(new String[]{merchantServiceId}, group.getGroupId(), group.getGroupName());
                        if(result.getCode() == 200){
                            group.setStoreServicerId(merchantServiceId);
                            ThreadPoolUtil.getPool().execute(()->iGroupService.updateById(group));
                            Optional.ofNullable(userService.getById(merchantServiceId))
                                    .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "merchantServicer")));

                            Optional.ofNullable(userService.getById(group.getPlatformServicerId()))
                                    .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "platformServicer")));

                            Optional.ofNullable(userService.getById(group.getUserId()))
                                    .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "user")));

                            Optional.ofNullable(userService.getById(group.getStoreId()))
                                    .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "merchant")));

                            groupInfoCreate.setGroupUsers(groupUsers);
                            groupInfoCreate.setGroupId(group.getGroupId());
                            groupInfoCreate.setGroupName(group.getGroupName());
                            return groupInfoCreate;
                        } else {
                            throw new RuanyunException("拉客服进群失败");
                        }
                    } catch (Exception e) {
                        throw new RuanyunException("系统异常");
                    }
                } else {
                    //商家没有客服
                    Optional.ofNullable(userService.getById(group.getPlatformServicerId()))
                            .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "platformServicer")));

                    Optional.ofNullable(userService.getById(group.getUserId()))
                            .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "user")));

                    Optional.ofNullable(userService.getById(group.getStoreId()))
                           .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "merchant")));

                    groupInfoCreate.setGroupUsers(groupUsers);
                    groupInfoCreate.setGroupId(group.getGroupId());
                    groupInfoCreate.setGroupName(group.getGroupName());
                    return groupInfoCreate;

                }
            } else {
                // 群组中有商家客服，直接返回
                Optional.ofNullable(userService.getById(group.getStoreServicerId()))
                        .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "merchantServicer")));

                Optional.ofNullable(userService.getById(group.getPlatformServicerId()))
                        .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "platformServicer")));

                Optional.ofNullable(userService.getById(group.getUserId()))
                        .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "user")));

                Optional.ofNullable(userService.getById(group.getStoreId()))
                        .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "merchant")));

                groupInfoCreate.setGroupUsers(groupUsers);
                groupInfoCreate.setGroupId(group.getGroupId());
                groupInfoCreate.setGroupName(group.getGroupName());
                return groupInfoCreate;
            }
        }

        // 商家客服
        String merchantServiceId = "";
        Map<String, Object> map2 = new HashMap<>();
        map2.put("create_by", merchantId);
        // 商家客服角色id  285894394777702400
        map2.put("role_id", "285894394777702400");
        List<UserRole> userRoles = iUserRoleService.listByMap(map2);
        // List<StoreServicer> storeServicers = (List<StoreServicer>) userRoles;
        if(userRoles.size() > 0){
            int chooseDindex = new Random().nextInt(userRoles.size());
            merchantServiceId = userRoles.get(chooseDindex).getUserId();
        }

        // 要添加的群组成员
        List<String> members = new ArrayList<>();

        // 平台客服
        String platformServiceId = null;


        List<UserRole> platformServicerList = iUserRoleService.list(Wrappers.<UserRole>lambdaQuery()
        .eq(UserRole::getRoleId, roleService.getIdByRoleName(CommonConstant.PC_SERVICE)));


        platformServicerList = platformServicerList.parallelStream().filter(userRole ->
                ToolUtil.isNotEmpty(userService.getById(userRole.getUserId())))
                .collect(Collectors.toList());

        if (ToolUtil.isNotEmpty(platformServicerList)) {

            int chooseDindex = new Random().nextInt(platformServicerList.size());
            platformServiceId = platformServicerList.get(chooseDindex).getUserId();

            log.info("平台客服 信息:" + platformServiceId);

            Optional.ofNullable(userService.getById(platformServiceId))
                    .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "platformServicer")));
            members.add(platformServiceId);
        }

        // 用户
        Optional.ofNullable(userService.getById(userId))
                .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "user")));
        members.add(userId);

        // 商家客服
        if(!"".equals(merchantServiceId)){
            Optional.ofNullable(userService.getById(merchantServiceId))
                    .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "merchantServicer")));
            members.add(merchantServiceId);
        }

        // 商家
        Optional.ofNullable(userService.getById(merchantId))
                .ifPresent(user -> groupUsers.add(new GroupUser(user.getId(), user.getAvatar(), user.getNickName(), "merchant")));

        // 群组id
        // String groupId = ToolUtil.getRandomString(24);// 最大30位
        String groupId = merchantId + "," + userId;

        // 群组名称
        String groupName = userService.getById(merchantId).getShopName();

        groupInfoCreate.setGroupUsers(groupUsers);
        groupInfoCreate.setGroupId(groupId);
        groupInfoCreate.setGroupName(groupName);

        log.info("当前群组的人是：" + groupUsers);

            // 创建群组
        CodeSuccessResult result = imClient.group.create(members.toArray(new String[]{}), groupId, groupName);
        if(result.getCode() == 200){
            Group group = new Group();
            group.setGroupId(groupId);
            group.setUserId(userId);
            if (ToolUtil.isNotEmpty(platformServiceId)) {

                group.setPlatformServicerId(platformServiceId);
            }

            group.setStoreServicerId(merchantServiceId);
            group.setStoreId(merchantId);
            group.setGroupName(groupName);
            iGroupService.insertOrderUpdateGroup(group);
            return groupInfoCreate;
        }else{
            throw new RuanyunException("创建群组失败");
        }
    }

    @Override
    public Object joinGroup(String groupId, String groupName, String[] member) {
        try {
            CodeSuccessResult result = imClient.group.join(member, groupId, groupName);
            if(result.getCode() == 200){
                Group group = iGroupService.getOne(Wrappers.<Group>lambdaQuery()
                        .eq(Group::getGroupId, groupId));
                String userId = group.getUserId();
                List<String> ids = Arrays.asList(userId.split(","));
                ids.addAll(Arrays.asList(member));
                group.setUserId(ids.toString());
                iGroupService.updateById(group);
                return new Object();
            }else{
                throw new RuanyunException("加入群组失败");
            }
        } catch (Exception e) {
            throw new RuanyunException("系统异常");
        }
    }

    @Override
    public Object updateGroup(String groupId, String groupName) {
        try {
            CodeSuccessResult result = imClient.group.refresh(groupId, groupName);
            if(result.getCode() == 200){
                Group group = iGroupService.getOne(Wrappers.<Group>lambdaQuery()
                        .eq(Group::getGroupId, groupId));
                group.setGroupName(groupName);
                iGroupService.updateById(group);
                return new Object();
            }else{
                throw new RuanyunException("更新群聊信息失败");
            }
        } catch (Exception e) {
            throw new RuanyunException("系统异常");
        }
    }

    @Override
    public Object quitGroup(String groupId, String[] member) {
        try {
            CodeSuccessResult result = imClient.group.quit(member, groupId);
            if(result.getCode() == 200){
                Group group = iGroupService.getOne(Wrappers.<Group>lambdaQuery()
                        .eq(Group::getGroupId, groupId));
                String userId = group.getUserId();
                List<String> ids = Arrays.asList(userId.split(","));
                for (String id: ids) {
                    for (String memberOne: member){
                        if (memberOne.equals(id)){
                            ids.remove(id);
                        }
                    }
                }
                iGroupService.updateById(group);
                return new Object();
            }else{
                throw new RuanyunException("退出群聊失败");
            }
        } catch (Exception e) {
            throw new RuanyunException("系统异常");
        }
    }

    @Override
    public Object dismissGroup(String groupId, String userId) {
        try {
            CodeSuccessResult result = imClient.group.dismiss(userId, groupId);
            if(result.getCode() == 200){
                Map<String, Object> removeGroup = new HashMap<>();
                removeGroup.put("group_id", groupId);
                boolean b = iGroupService.removeByMap(removeGroup);
                log.info("移除群组" + groupId + "结果: " + b);
                return new Object();
            }else{
                throw new RuanyunException("解散群聊失败");
            }
        } catch (Exception e) {
            throw new RuanyunException("系统异常");
        }
    }

    @Override
    public Object addGagUser(String userId, String groupId, String minute) {
        try {
            CodeSuccessResult result = imClient.group.addGagUser(userId, groupId, minute);
            if(result.getCode() == 200){
                return new Object();
            }else{
                throw new RuanyunException("禁言成功");
            }
        } catch (Exception e) {
            throw new RuanyunException("系统异常");
        }
    }

    @Override
    public Object lisGagUser(String groupId) {
        try {
            ListGagGroupUserResult listGagGroupUserResult = imClient.group.lisGagUser(groupId);
            // 禁言成员列表
             List<GagGroupUser> users = listGagGroupUserResult.getUsers();
            if(listGagGroupUserResult.getCode() == 200){
                return users;
            }else{
                throw new RuanyunException("查询被禁言成员成功");
            }
        } catch (Exception e) {
            throw new RuanyunException("系统异常");
        }
    }

    @Override
    public Object rollBackGagUser(String[] userId, String groupId) {
        try {
            CodeSuccessResult result = imClient.group.rollBackGagUser(userId, groupId);
            if(result.getCode() == 200){
                return new Object();
            }else{
                throw new RuanyunException("移除被禁言成员成功");
            }
        } catch (Exception e) {
            throw new RuanyunException("系统异常");
        }
    }

    @Override
    public Map<String, Object> getUserByGroupId(String groupId) {
        Group group = iGroupService.getOne(Wrappers.<Group>lambdaQuery()
                .eq(Group::getGroupId, groupId));
        System.out.println(group);
        String userId = group.getUserId();
        List<String> ids = Arrays.asList(userId.split(","));
        Map<String, Object> map = new HashMap<>();
        map.put("user", iUserService.listByIds(ids));


        map.put("store_servicer", iUserService.getOne(Wrappers.<User>lambdaQuery()
                .eq(User::getId, group.getStoreServicerId())));

        map.put("platform_servicer", iUserService.getOne(Wrappers.<User>lambdaQuery()
                .eq(User::getId, group.getPlatformServicerId())));

        return map;
    }

    @Override
    public Object getGroupListByUserId(String userId) {
        List<Group> groups = new ArrayList<>();
        Map<String, Object> user1 = new HashMap<>();
        user1.put("user_id", userId);


        groups.addAll(iGroupService.listByMap(user1));


        Map<String, Object> user2 = new HashMap<>();
        user2.put("store_servicer_id", userId);
        groups.addAll(iGroupService.listByMap(user2));

        Map<String, Object> user3 = new HashMap<>();
        user3.put("platform_servicer_id", userId);
        groups.addAll(iGroupService.listByMap(user3));


        /**
        if(group1.size() == 0){
            Map<String, Object> user2 = new HashMap<>();
            user2.put("store_servicer_id", userId);
            List<Group> group2 = iGroupService.listByMap(user2);
            if(group2.size() == 0){
                Map<String, Object> user3 = new HashMap<>();
                user3.put("platform_servicer_id", userId);
                List<Group> group3 = iGroupService.listByMap(user3);
                if(group3.size() == 0){
                    return new ArrayList<>();
                } else {
                    groups = group3;
                }
            } else {
                groups = group2;
            }
        } else {
            groups = group1;
        }*/

        List<Map<String, Object>> list = new ArrayList<>();
        for (Group group: groups) {
            Map<String, Object> back = new HashMap<>();
            back.put("group_id", group.getGroupId());
            back.put("group_name", group.getGroupName());

            List<User> userList = iUserService.listByIds(Arrays.asList(group.getUserId().split(",")));
            List<GroupUserVO> groupUserVOList = new ArrayList<>();
            for (User user : userList) {
                groupUserVOList.add(new GroupUserVO(user.getId(), user.getAvatar(), user.getNickName()));
            }
            back.put("user", Optional.ofNullable(ToolUtil.setListToNul(userList)).map(users -> users.get(0)).orElse(null));

            User store_servicer = iUserService.getOne(Wrappers.<User>lambdaQuery()
                    .eq(User::getId, group.getStoreServicerId()));
            if(EmptyUtil.isNotEmpty(store_servicer)){
                back.put("store_servicer", new GroupUserVO(store_servicer.getId(), store_servicer.getAvatar(), store_servicer.getNickName()));
            }

            User platform_servicer = iUserService.getOne(Wrappers.<User>lambdaQuery()
                    .eq(User::getId, group.getPlatformServicerId()));
            if (ToolUtil.isNotEmpty(platform_servicer)) {

                back.put("platform_servicer", new GroupUserVO(platform_servicer.getId(), platform_servicer.getAvatar(), platform_servicer.getNickName()));
            }

            //空指针
           Optional.ofNullable(iUserService.getOne(Wrappers.<User>lambdaQuery()
                   .eq(User::getId, group.getStoreId())))
                   .ifPresent(store1 -> back.put("store", new GroupUserVO(store1.getId(), store1.getAvatar(), store1.getShopName())));
            list.add(back);
        }
        return list;
    }

    @Override
    public Result<Object> registerRongyun(RongyunImDto rongyunImDto) {
        System.out.println("注册用户" + rongyunImDto);
        Boolean aBoolean = this.addUser(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()) ,rongyunImDto.getNickname() , CommonConstant.USER_DEFAULT_AVATAR);
        return aBoolean? new ResultUtil<>().setSuccessMsg("注册成功！") : new ResultUtil<>().setErrorMsg("注册失败！");

        /** 以下为原代码 */

        /**
        //1发送短信接口
        JSONObject sendMessageParam = new JSONObject();
        sendMessageParam.put("region", 86);
        sendMessageParam.put("phone", rongyunImDto.getPhone());


        String sendMessageResult = HttpUtil.post("http://hqhh520.com:8585/user/send_code_yp", sendMessageParam.toJSONString());

        log.info(sendMessageResult);
        if ("200".equals(JSONObject.parseObject(sendMessageResult).getString("code"))) {

            log.info("调用短信接口成功!");
            JSONObject verifyMessageParam = new JSONObject();
            verifyMessageParam.put("region", "86");
            verifyMessageParam.put("code", "111");
            verifyMessageParam.put("phone", rongyunImDto.getPhone());

            //2.调用有效短信接口
            String verifyMessageResult = HttpUtil.post("http://hqhh520.com:8585/user/verify_code_yp", verifyMessageParam.toJSONString());

            if ("200".equals(JSONObject.parseObject(verifyMessageResult).getString("code"))) {

                log.info("调用验证短信成功!");
                JSONObject jsonObject = JSONObject.parseObject(verifyMessageResult).getJSONObject("result");
                String verificationToken = jsonObject.getString("verification_token");


                //调用注册接口
                JSONObject registerParam = new JSONObject();
                registerParam.put("nickname", rongyunImDto.getNickname());
                registerParam.put("password", "123456");
                registerParam.put("verification_token", verificationToken);
                registerParam.put("phone", rongyunImDto.getPhone());

                String registerResult = HttpUtil.post("http://hqhh520.com:8585/user/register", registerParam.toJSONString());
                System.out.println("HTTP调用注册接口返回数据"+ registerResult);
                if ("200".equals(JSONObject.parseObject(registerResult).getString("code"))) {

                    log.info("注册成功");
                }else {

                    return new ResultUtil<>().setErrorMsg(JSONObject.parseObject(registerResult).getIntValue("code"), JSONObject.parseObject(sendMessageResult).getString("msg"));
                }

            }else {
                return new ResultUtil<>().setErrorMsg(JSONObject.parseObject(verifyMessageResult).getIntValue("code"), JSONObject.parseObject(sendMessageResult).getString("msg"));

            }
        }else {

            return new ResultUtil<>().setErrorMsg(JSONObject.parseObject(sendMessageResult).getIntValue("code"), JSONObject.parseObject(sendMessageResult).getString("msg"));
        }*/

        //  注册融云成功
        // return new ResultUtil<>().setSuccessMsg("注册成功！");
    }

    @Override
    public RongyunLoginVo loginRongyun(RongyunImDto rongyunImDto) {
        System.out.println("登陆操作" + rongyunImDto);

        User user = iUserService.getOne(Wrappers.<User>lambdaQuery().eq(User::getMobile, rongyunImDto.getPhone()));
        String s = this.getToken(user.getId(), user.getNickName(), user.getAvatar());
        RongyunLoginVo rongyunLoginVo = new RongyunLoginVo();
        rongyunLoginVo.setId(user.getId()).setToken(s);

        return rongyunLoginVo;

        /** 以下为原代码

        JSONObject param = new JSONObject();
        param.put("phone", rongyunImDto.getPhone());
        param.put("region", "86");
        param.put("password", "123456");

        String result = HttpUtil.post("http://hqhh520.com:8585/user/login", param.toJSONString());
        System.out.println("调用HTTP登录接口返回数据" + result);
        if ("200".equals(JSONObject.parseObject(result).getString("code"))) {

            log.info("调用登陆接口成功!");
            JSONObject jsonObject = JSONObject.parseObject(result).getJSONObject("result");
            String id = jsonObject.getString("id");
            String token = jsonObject.getString("token");

            RongyunLoginVo rongyunLoginVo = new RongyunLoginVo();
            rongyunLoginVo.setId(id).setToken(token);

            return rongyunLoginVo;
        }

        return null;
         */
    }

}